<?php

class ContentAction extends PublicAction
{
    //当前栏目id
    protected $catid = 0;
    protected $db;
    protected $fields;
    protected $modelid;
    protected $type;
    protected $modelName;
    protected $adminTplPath;

    public function _initialize()
    {
        parent::_initialize();
        $this->catid = $catId = I('request.catid', 0, 'intval');
        $this->modelName = MODULE_NAME;
        $this->modelid = $this->Mod[MODULE_NAME];
        $this->db = D($this->modelName);
        if ($this->Categorys) {

            $array = $this->Categorys;
            foreach ($array as $k=>$r) {
                if ($r['modelid'] != $this->modelid || $r['child']) {
                    $array[$k]['disabled'] = $r['child'] ? ' disabled' : '';
                } else {
                    $array[$k]['disabled'] = '';
                }
                $arr = explode(",", $r['arrchildid']);

                foreach ($arr as $rr) {
                    if (!$array[$rr]['child']) {
                        if ($array[$rr]['type'] > 0 || $array[$rr]['modelid'] != $this->modelid) {
                            unset($array[$rr]);
                        }
                    }
                }
            }

            import('@.ORG.Tree');
            $tree = new Tree($array);
            $select_categories = $tree->get_tree(0, $this->catid, 'catname');
            $this->assign('select_categorys', $select_categories);
            $this->assign('categorys', $this->Categorys);

            $this->assign('posids', getCache('Posid'));
        }

        $fields = getCache('Field_' . $this->modelid);

        foreach ($fields as $key => $res) {
            if ($res['status'] == 1) {
                $res['setup'] = json_decode($res['setup'], true);
                $this->fields[$key] = $res;
            }
        }
        $this->assign('fields', $this->fields);
        $this->assign('model', $this->Model);
    }

    public function index()
    {
        $model = M($this->modelName);

        $_REQUEST['listRows'] = I('listRows', 15, 'intval');
        $order = $_REQUEST['order'] = I('order', 'id');
        $sort = $_REQUEST['sort'] = I('sort', 'desc');
        $keyword = $_REQUEST['keyword'] = I('keyword', '');
        $searchtype = $_REQUEST['searchtype'] = I('searchtype', '');
        $_REQUEST['groupid'] = I('groupid', 0, 'intval');
        $_REQUEST['catid'] = I('catid', 0, 'intval');
        $_REQUEST['posid'] = I('posid', 0, 'intval');
        $_REQUEST['typeid'] = I('typeid', 0, 'intval');

        $map = array();

        $map['lang'] = array('eq', LANG_ID);

        if (!empty($keyword) && !empty($searchtype)) {
            $map[$searchtype] = array('like', '%' . $keyword . '%');
        }

        if ($_REQUEST['groupid'])
            $map['groupid'] = $_REQUEST['groupid'];

        if ($_REQUEST['catid'])
            $map['catid'] = $_REQUEST['catid'];

        if ($_REQUEST['posid']) {
            $map['posid'] = array('like', '%-' . $_REQUEST['posid'] . '-%');
        }

        if ($_REQUEST['typeid'])
            $map['typeid'] = $_REQUEST['typeid'];

        if (!empty($_REQUEST['map'])) {
            foreach ($_REQUEST['map'] as $key => $res) {
                if (($res === '0' || $res > 0) || !empty($res)) {
                    if ($_REQUEST['maptype'][$key]) {
                        $map[$key] = array($_REQUEST['maptype'][$key], $res);
                    } else {
                        $map[$key] = intval($res);
                    }
                    $_REQUEST[$key] = $res;
                } else {
                    unset($_REQUEST[$key]);
                }
            }
        }

        $this->assign($_REQUEST);

        //取得满足条件的记录总数
        $count = $model->where($map)->count('id');
        //echo $model->getLastsql();

        //初始化分页变量
        $page = '';
        if ($count > 0) {
            import("@.ORG.Page");
            //创建分页对象
            $p = new Page($count, $_REQUEST['listRows']);

            //分页查询数据
            $field = $this->Model[$this->modelid]['listfields'];
            $field = (empty($field) || $field == '*') ? '*' : 'id,catid,url,posid,title,thumb,title_style,user_id,username,hits,create_time,update_time,status,listorder';
            $voList = $model->field($field)->where($map)->order("`" . $order . "` " . $sort)->limit($p->firstRow . ',' . $p->listRows)->select();

            //分页跳转的时候保证查询条件
            $p->parameter = '';
            foreach ($map as $key => $val) {
                if (!is_array($val)) {
                    $p->parameter .= "$key=" . urlencode($val) . "&";
                }
            }

            //分页显示
            $page = $p->show();

            //模板赋值显示
            $this->assign('list', $voList);
        }

        //记录当前位置
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $this->assign('page', $page);

        $template = file_exists($this->adminTplPath . 'index.html') ? MODULE_NAME . ':index' : 'Content:index';
        $this->display($template);
    }

    //新增
    public function add()
    {
        if (IS_POST) {
            $catid = $_POST['catid'] = intval($_POST['catid']);
            if (empty($catid)) {
                $this->error("请选择栏目！");
            }

            //防止重复提交
            if (!checkToken($_POST['TOKEN'])) {
                //return;
            }

            import('@.Service.Content');
            $content = new Content();
            try {
                $id = $content->add($_POST);
                if ($id !== false) {
                    $data = '';
                    $cat = $this->Categorys[$catid];
                    $url = geturl($cat, $_POST, $this->Urlrule);

                    $data['id'] = $id;
                    $data['url'] = $url[0];

                    $model = $this->db;
                    $model->save($data);

                    if ($_POST['keywords']) {
                        $keywordsarr = explode(',', $_POST['keywords']);
                        $i = 0;

                        $tagsdata = M('Tags_data');
                        $tagsdata->where("id=" . $id)->delete();

                        foreach ((array)$keywordsarr as $tagname) {

                            if ($tagname) {

                                $tagidarr = $tagdatas = $where = array();
                                $where['name'] = array('eq', $tagname);
                                $where['modelid'] = array('eq', $cat['modelid']);
                                $tag = M('Tags')->where($where)->field('id')->find();
                                $tagidarr['id'] = $id;

                                if ($tag['id']) {
                                    $num = $tagsdata->where("tagid=" . $tag['id'])->count();
                                    $tagdatas['num'] = $num + 1;
                                    M('Tags')->where("id=" . $tag['id'])->save($tagdatas);
                                    $tagidarr['tagid'] = $tag['id'];
                                } else {
                                    $tagdatas['modelid'] = $cat['modelid'];
                                    $tagdatas['name'] = $tagname;
                                    $tagdatas['slug'] = Pinyin($tagname);
                                    $tagdatas['num'] = 1;
                                    $tagdatas['lang'] = $_POST['lang'];
                                    $tagdatas['model'] = $cat['model'];
                                    $tagidarr['tagid'] = M('Tags')->add($tagdatas);
                                }
                                $i++;
                                $tagsdata->add($tagidarr);
                            }
                        }
                    }

                    $this->success('添加成功！');
                } else {
                    $this->error('提交失败！');
                }
            } catch(Exception $e){
                $this->error($e->getMessage());
            }

        } else {

            $template = file_exists($this->adminTplPath . 'edit.html') ? MODULE_NAME . ':edit' : 'Content:add';

            import("@.ORG.Form");
            $form = new Form(array('catid'=>$this->catid));
            $this->assign('form', $form);

            //创建token
            createToken();

            $this->display($template);
        }
    }

    //编辑
    public function edit()
    {
        if (IS_POST) {
            $catid = intval($_POST['catid']);
            if (empty($catid)) {
                $this->error("请选择栏目！");
            }
            //防止重复提交
            if (!checkToken($_POST['TOKEN'])) {
                //return;
            }

            import('@.Service.Content');
            $content = new Content();
            try {
                // 更新数据
                $list = $content->save($_POST);

                if (false !== $list) {
                    $id = $_POST['id'];

                    if ($_POST['keywords']) {

                        $keywordsarr = explode(',', $_POST['keywords']);
                        $i = 0;
                        $tagsdata_db = M('Tags_data');
                        $tagsdata_db->where("id=" . $id)->delete();

                        foreach ((array)$keywordsarr as $tagname) {
                            if ($tagname) {
                                $tagidarr = $tagdatas = $where = array();
                                $where['name'] = array('eq', $tagname);
                                $where['modelid'] = array('eq', $cat['modelid']);
                                $tag = M('Tags')->where($where)->field('id')->find();
                                $tagidarr['id'] = $id;

                                if ($tag['id']) {
                                    $num = $tagsdata_db->where("tagid=" . $tag['id'])->count();
                                    $tagdatas['num'] = $num + 1;
                                    M('Tags')->where("id=" . $tag['id'])->save($tagdatas);
                                    $tagidarr['tagid'] = $tag['id'];
                                } else {
                                    $tagdatas['modelid'] = $cat['modelid'];
                                    $tagdatas['name'] = $tagname;
                                    $tagdatas['slug'] = Pinyin($tagname);
                                    $tagdatas['num'] = 1;
                                    $tagdatas['lang'] = LANG_ID;
                                    $tagdatas['model'] = $cat['model'];
                                    $tagidarr['tagid'] = M('Tags')->add($tagdatas);
                                }

                                $i++;
                                $tagsdata_db->add($tagidarr);
                            }
                        }
                    }
                    $this->success('修改成功!');

                } else {
                    //错误提示
                    $this->error('修改失败!' );
                }
            } catch (Exception $e) {
                $this->error($e->getMessage());
            }

        } else {

            $id = I('id');
            $vo = $this->db->getById($id);

            $vo['content'] = htmlspecialchars($vo['content']);

            import("@.ORG.Form");
            $form = new Form($vo);

            $this->assign($_REQUEST);
            $this->assign('vo', $vo);
            $this->assign('form', $form);
            $template = file_exists($this->adminTplPath . 'edit.html') ? $modelname . ':edit' : 'Content:edit';
            //创建token
            createToken();

            $this->display($template);
        }
    }

    //推送
    public function push()
    {
        if (IS_POST) {
            $id = I('post.id');
            $modelid = $this->modelid;
            $model_db = D($this->modelName);
            $action = I('get.action');
            if (!$id || !$action || !$modelid) {
                $this->error('参数不正确');
            }
            switch ($action) {
                //推荐位
                case "position_list":
                    $posid = $_POST['posid'];
                    if ($posid && is_array($posid)) {
                        $ids = explode('|', $id);
                        $idArr = implode(',', $ids);
                        $where = "id in(" . $idArr . ")";
                        $data['posid'] = '-' . implode('-', $posid) . '-';

                        $model_db->where($where)->data($data)->save();

                        $this->success('推送到推荐位成功！');
                    } else {
                        $this->error('请选择推荐位！');
                    }
                    break;
                //同步发布到其他栏目
                case 'push_to_category':
                    $catid = I('post.catid');
                    $ids = explode('|', $id);

                    if (!$catid) {
                        $this->error('请选择需要推送的栏目！');
                    }

                    foreach ($ids as $k => $aid) {
                        //取得信息
                        $r = $model_db->find($aid);
                        $keyid = strtolower($modelname) . '-' . $aid;
                        $aid_arr = M('AttachmentIndex')->field('aid')->where(array('keyid' => $keyid))->select();
                        //去除ID
                        unset($r['id']);
                        $r['catid'] = $catid;
                        $r['id'] = $model_db->add($r);
                        //添加附件关联信息
                        foreach ($aid_arr as $aid_item) {
                            $data['aid'] = $aid_item['aid'];
                            $data['keyid'] = strtolower($modelname) . '-' . $r['id'];
                            M('AttachmentIndex')->add($data);
                        }

                        //更新信息url地址
                        $url = geturl($this->Categorys[$r['catid']], $r, $this->Urlrule);
                        $r['url'] = $url['0'];
                        $model_db->save($r);
                    }
                    $this->success('推送其他栏目成功！');
                    break;
                default:
                    $this->error('请选择操作！');
                    break;
            }

        } else {
            $id = I('get.id');
            $action = I('get.action');
            $catid = $this->catid;
            $modelid = $this->modelid;

            if (!$id || !$action || !$modelid) {
                $this->error('参数不正确！');
            }
            $tpl = $action == 'position_list' ? 'push_list' : 'push_to_category';

            switch ($action) {
                //推荐位
                case 'position_list':
                    break;
                //同步发布到其他栏目
                case 'push_to_category':
                    break;
                default:
                    $this->error('请选择操作！');
                    break;
            }

            $this->assign('id', $id)
                ->assign('action', $action)
                ->assign('modelid', $modelid)
                ->assign('catid', $this->catid)
                ->display('Content:' . $tpl);
        }
    }

    //移动
    public function remove()
    {
        if (IS_POST) {
            $model_db = D($this->modelName);
            $id = I('post.id');
            if (!$id) {
                $this->error('参数不正确');
            }

            $ids = explode('|', $id);
            $idArr = implode(',', $ids);
            $where = "id in(" . $idArr . ")";

            $data['status'] = '1';

            if (!empty($_POST['catid'])) {

                $list = $model_db->field('id,catid,url')->where($where)->select();

                foreach ($list as $r) {
                    //if($r['islink']) continue;

                    $r['catid'] = intval($_POST['catid']);
                    $url = geturl($this->Categorys[$r['catid']], $r, $this->Urlrule);

                    $r['url'] = $url['0'];

                    $model_db->save($r);
                }
            }
            $this->success('移动成功！');
        } else {
            $id = I('get.id');
            $modelid = $this->modelid;

            if (!$id || !$modelid) {
                $this->error('参数不正确！');
            }

            $this->assign('id', $id)
                ->assign('modelid', $modelid)
                ->display('Content:remove');
        }
    }

    //删除数据
    public function delete()
    {
        $model_db = D($this->modelName);

        $id = I('get.id');
        if (!$id) {
            $this->error('参数不正确！');
        }

        if (false !== $model_db->delete($id)) {
            $this->success('删除成功！');
        } else {
            $this->error('删除失败！: ' . $model_db->getDbError());
        }

    }

    //排序
    public function sort()
    {
        $model_db = M($this->modelName);
        $pk = $model_db->getPk();
        $ids = $_POST['listorders'];

        foreach ($ids as $key => $r) {
            $data['listorder'] = $r;
            $model_db->where($pk . '=' . $key)->save($data);
        }

        $this->success('提交成功!');
    }

    //相关文章选择
    public function public_relationlist()
    {
        if (IS_POST) {
            $modelid = getCategory($this->catid, 'modelid');
            $_POST['modelid'] = $modelid;
            $this->redirect('public_relationlist', $_POST);
        }
        $modelid = I('get.modelid', 0, 'intval');
        if (empty($modelid)) {
            $this->error('缺少参数！');
        } else {
            $modelid = I('get.modelid', 0, 'intval');
            $model = ContentModel::getInstance($modelid);
            $where = array();
            $catid = $this->catid;
            if ($catid) {
                $where['catid'] = $catid;
            }
            $where['status'] = 1;
            $where['lang'] = LANG_ID;
            if (isset($_GET['keywords'])) {
                $keywords = trim($_GET['keywords']);
                $field = $_GET['searchtype'];
                if (in_array($field, array('id', 'title', 'keywords', 'description'))) {
                    if ($field == 'id') {
                        $where['id'] = array('eq', $keywords);
                    } else {
                        $where[$field] = array('like', '%' . $keywords . '%');
                    }
                }
            }
            $count = $model->where($where)->count();
            import("@.ORG.Page");
            $page = new Page($count, 10);
            $data = $model->where($where)->limit($page->firstRow . ',' . $page->listRows)->order(array('id' => "DESC"))->select();

            import('@.ORG.Tree');
            $categorys = M('Category')->where('modelid='.$modelid)->select();
            $tree = new Tree($categorys);
            $select_categorys = $tree->get_tree(0, $catid, 'catname');

            $this->assign('select_categorys', $select_categorys);
            $this->assign('data', $data);
            $this->assign('Page', $page->show());
            $this->assign('modelid', $modelid);
            $this->assign('field', $_GET['field']);
            $this->display('relationlist');
        }
    }

    //更改状态
    public function setStatus()
    {
        $model_db = M($this->modelName);

        $id = I('get.id', '');
        $status = I('status', 0);
        if (!$id) {
            $this->error('没有信息被选中！');
        }

        $data = $model_db->select($id);

        foreach ($data as $key => $r) {
            $model_db->save(array('id' => $r['id'], 'status' => $status));
        }

        $this->success('审核成功！');
    }

}